<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="500px"
    :before-close="handleClose"
  >
    <!-- v-loading 的值为true显示加载中 -->
    <el-form ref="formData" v-loading="loading" label-width="80px">
      <el-tree
        ref="tree"
        :data="menuList"
        show-checkbox
        node-key="id"
        :props="{ children: 'children', label: 'name' }"
        accordion
        :default-checked-keys="menuIds"
      >
        <!-- accordion 手风琴模式点击一个展开其他的收起来，:props定义children和label的绑定的属性，
            :default-checked-keys默认选中哪一个  show-checkbox显示勾选框-->
      </el-tree>
      <el-form-item>
        <el-button type="primary" @click="submitForm('formData')" size="mini"
          >确定</el-button
        >
        <el-button size="mini" @click="handleClose">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import menuApi from "@/api/menu";
import roleApi from "@/api/role";
export default {
  props: {
    title: {
      //弹窗的标题
      type: String,
      default: "",
    },
    visible: {
      //弹出窗口
      type: Boolean,
      default: false,
    },

    remoteClose: Function, //用于关闭窗口
    roleId: null,
  },
  data() {
    return {
      menuList: [],
      loading: false,
      menuIds: [],
      checkedMenuIds: [],
    };
  },
  watch: {
    visible(val) {
      if (val == true) {
        // this.visible 为true则加载所有菜单
        this.getMenuList();
      }
    },
  },
  methods: {
    submitForm(formName) {
      //获取所有被选中的ID
      const checkedMenuIds = this.$refs.tree.getCheckedKeys();
      roleApi.saveRoleMenu(this.roleId, checkedMenuIds).then((res) => {
        if (res.code === 20000) {
          this.$message({ message: "权限分配成功", type: "success" });
          this.handleClose();
        } else {
          this.$message({ message: "失败", type: "error" });
        }
      });
    },
    handleClose() {
      this.menuList = [];
      this.menuIds = [];
      this.remoteClose();
    },
    //获取所有菜单
    getMenuList() {
      //加载中
      this.loading = true;
      menuApi.getList({}).then((res) => {
        this.menuList = res.data;
        this.getMenuIds();
      });
      //加载完成
      this.loading = false;
    },
    getMenuIds() {
      roleApi.getMenuIds(this.roleId).then((res) => {
        this.menuIds = res.data;
      });
    },
  },
};
</script>
<style>
</style>